﻿using System;
using System.IO;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media.Imaging;
using Avalonia.Platform.Storage;

namespace DevHub.WindowsApp.Pages.Encode;

public partial class Base64ImageView : UserControl
{
    public Base64ImageView()
    {
        InitializeComponent();
        Image = this.FindControl<Image>("Image");
        Box = this.FindControl<TextBox>("Box");
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
    }

    private async void ChooseImageClick(object? sender, RoutedEventArgs e)
    {
        var top = TopLevel.GetTopLevel(this);
        if (top == null) return;
        var resultList =
            await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions() { AllowMultiple = false });
        if (resultList.Count == 0) return;
        try
        {
            Image.Source = new Bitmap(resultList[0].Path.LocalPath);
            Box.Text = $"data:image/png;base64{Environment.NewLine}" +
                       Convert.ToBase64String(await File.ReadAllBytesAsync(resultList[0].Path.LocalPath));
        }
        catch
        {
            Image.Source = null;
        }
    }

    private void TextChanged(object? sender, TextChangedEventArgs e)
    {
        if (string.IsNullOrEmpty(Box.Text)) return;
        try
        {
            var bytes = Convert.FromBase64String(Box.Text.Replace("data:image/png;base64", ""));
            Image.Source = new Bitmap(new MemoryStream(bytes));
        }
        catch
        {
            Image.Source = null;
        }
    }

    private void CopyClick(object? sender, RoutedEventArgs e)
    {
        if(string.IsNullOrEmpty(Box.Text))return;
        var top = TopLevel.GetTopLevel(this);
        top?.Clipboard?.SetTextAsync(Box.Text);
    }

    private void DeleteClick(object? sender, RoutedEventArgs e)
    {
        Box.Text = "";
    }

    private void DeleteImageClick(object? sender, RoutedEventArgs e)
    {
        Image.Source = null;
    }
}